<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="550px"
            :clickModalClose="true"
            @confirm="handleSubmit"
            @close="handleClose"
            :confirmButtonText="isDetail ? '确认' : false"
        >
            <div v-if="!isDetail">
                <h2 style="height: 28px">个人信息</h2>
                <div style="display: flex; width: 100%">
                    <div style="width: 50%">
                        <h3>真实姓名：{{formData.realname}}</h3>
                        <h3>联系方式：{{formData.mobile}}</h3>
                        <h3>身份证号：{{formData.idNumber}}</h3>
                        <h3>所属律所：{{formData.lawOffice}}</h3>
                        <h3>申请时间：{{createdAtStr}}</h3>
                    </div>
                    <div style="width: 50%">
                        <h3>性别：{{sexStr}}</h3>
                        <h3>所属地区：{{formData.areaName}}</h3>
                        <h3>工作类型：{{jobTypeStr}}</h3>
                        <h3>从业开始时间：{{formData.workBeginDate}}</h3>
                        <h3>工作年限：{{formData.workYears}}年</h3>
                    </div>
                </div>
                <hr style="margin:10px 0px;color: #d5d7de"/>
                <h2 style="height: 28px">擅长领域</h2>
                <h3>{{formData.skilledField}}</h3>
                <hr style="margin:10px 0px;color: #d5d7de"/>
                <h2 style="height: 28px">业务范围</h2>
                <h3>{{formData.businessScope}}</h3>
                <hr style="margin:10px 0px;color: #d5d7de"/>
                <h2 style="height: 28px">其他信息</h2>
                <h3>职业证书文件：</h3>
                <div style="display: flex; width: 100%; flex-wrap: wrap">
                    <img v-for="(item, index) in lawyerCertFilesArr" :key="index"
                         style="margin: 10px 10px;width: 50px; height: 50px; box-shadow: 1px 1px 1px #888888; object-fit: contain"
                         :src="item" @click="handlePreview(item)">
                </div>
                <h3>其他辅助证书文件：</h3>
                <div style="display: flex; width: 100%; flex-wrap: wrap">
                    <img v-for="(item, index) in otherCertFilesArr" :key="index"
                         style="margin: 10px 10px;width: 50px; height: 50px; box-shadow: 1px 1px 1px #888888; object-fit: contain"
                         :src="item" @click="handlePreview(item)">
                </div>
                <h3>身份证照片：</h3>
                <div style="display: flex; width: 100%; flex-wrap: wrap">
                    <img v-for="(item, index) in idCardFilesArr" :key="index"
                         style="margin: 10px 10px;width: 50px; height: 50px; box-shadow: 1px 1px 1px #888888; object-fit: contain"
                         :src="item" @click="handlePreview(item)">
                </div>

            </div>
            <div v-else>
                <el-form ref="formRef" :model="formData" label-width="84px" :rules="formRules" label-position="top">
                    <el-form-item label="真实姓名" prop="realname">
                        <el-input v-model="formData.realname" placeholder="请输入真实姓名" />
                    </el-form-item>
                    <el-form-item label="性别" prop="gender">
                        <el-radio-group v-model="formData.gender" placeholder="性别">
                            <el-radio
                                v-for="(item, index) in dictData.sex2"
                                :key="index"
                                :label="item.value"
                                :disabled="!item.status"
                            >
                                {{ item.name }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="身份证号" prop="idNumber">
                        <el-input v-model="formData.idNumber" placeholder="请输入身份证号" />
                    </el-form-item>
                    <el-form-item label="联系方式-手机号" prop="mobile">
                        <el-input v-model="formData.mobile" placeholder="请输入联系方式-手机号" />
                    </el-form-item>
                    <el-form-item label="所属律所" prop="lawOffice">
                        <el-input v-model="formData.lawOffice" placeholder="请输入所属律所" />
                    </el-form-item>
                    <el-form-item label="律所地址" prop="lawOfficeAddress">
                        <el-input v-model="formData.lawOfficeAddress" placeholder="请输入律所地址" />
                    </el-form-item>
                    <el-form-item label="从业开始时间" prop="workBeginDate">
                        <el-date-picker
                            class="flex-1 !flex"
                            v-model="formData.workBeginDate"
                            type="date"
                            clearable
                            value-format="YYYY-MM-DD"
                            placeholder="请选择从业开始时间"
                        />
                    </el-form-item>
                    <el-form-item label="执业分类" prop="jobType">
                        <el-radio-group v-model="formData.jobType" placeholder="执业分类">
                            <el-radio
                                v-for="(item, index) in dictData.job_type"
                                :key="index"
                                :label="item.value"
                                :disabled="!item.status"
                            >
                                {{ item.name }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="职业证书文件" prop="lawyerCertFiles">
                        <div class="flex-1">
                            <!-- 外层需要有足够的宽度，这样预览图和选择按钮才不会直接换行 -->
                            <material-picker :limit="4" v-model="lawyerCertFilesArr" />
                        </div>
                    </el-form-item>
                    <el-form-item label="其他辅助证书文件" prop="otherCertFiles">
                        <div class="flex-1">
                            <!-- 外层需要有足够的宽度，这样预览图和选择按钮才不会直接换行 -->
                            <material-picker :limit="4" v-model="otherCertFilesArr" />
                        </div>
                    </el-form-item>
                    <el-form-item label="身份证照片" prop="idCardFiles">
                        <div class="flex-1">
                            <!-- 外层需要有足够的宽度，这样预览图和选择按钮才不会直接换行 -->
                            <material-picker :limit="4" v-model="idCardFilesArr" />
                        </div>
                    </el-form-item>
                    <el-form-item label="擅长领域" prop="skilledField">
                        <el-input
                            v-model="formData.skilledField"
                            placeholder="请输入擅长领域"
                            type="textarea"
                            :autosize="{ minRows: 4, maxRows: 6 }"
                        />
                    </el-form-item>
                    <el-form-item label="业务范围" prop="businessScope">
                        <el-input
                            v-model="formData.businessScope"
                            placeholder="请输入业务范围"
                            type="textarea"
                            :autosize="{ minRows: 4, maxRows: 6 }"
                        />
                    </el-form-item>
                    <el-form-item label="所属销售" prop="salesman">
                        <el-select class="flex-1" v-model="formData.salesman" placeholder="请选择销售人员">
                            <el-option v-for="(item, index) in optionsData.businessList" :key="index" :label="item.nickname" :value="item.id"/>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
        </popup>
        <preview v-model="showPreview" :url="previewUrl" type="image" />
    </div>
</template>
<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import {  lawyerEdit, lawyerAdd, lawyerDetail, allBusiness } from '@/api/lawyer'
import Popup from '@/components/popup/index.vue'
import feedback from '@/utils/feedback'
import type { PropType } from 'vue'
import {timeFormat} from "@/utils/util";
import FileItem from '@/components/material/file.vue'
import Preview from '@/components/material/preview.vue'
import {useDictOptions} from "@/hooks/useDictOptions";
import {allCourtClerk} from "@/api/customer";

let diclist = defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showPreview = ref(false)
const previewUrl = ref('')
const { optionsData } = useDictOptions<{
    businessList: any[]
}>({
    businessList: {
        api: allBusiness
    }
})

const popupTitle = computed(() => {
    if (mode.value == 'add') {
        return '新增'
    } else if (mode.value == 'edit') {
        return '编辑'
    } else {
        return '详情'
    }
})
const sexStr = computed(() => {
    if (formData.gender === 1) {
        return '男';
    } else if (formData.gender === 2) {
        return '女';
    } else {
        return '未知';
    }
})

const jobTypeStr = computed(() => {
    if (formData.jobType === 1) {
        return '全职律师';
    } else if (formData.jobType === 2) {
        return '兼职律师';
    } else {
        return '未知';
    }
})
const createdAtStr = computed(() => {
    return timeFormat(formData.createdAt, 'yyyy-mm-dd hh:MM:ss');
})
const lawyerCertFilesArr = computed({
    get() {
        let parse = [];
        if (formData.lawyerCertFiles) {
            parse = JSON.parse(formData.lawyerCertFiles);
        }
        return parse;
    },
    set(newValue) {
        formData.lawyerCertFiles = JSON.stringify(newValue)
    }
})
const otherCertFilesArr = computed({
    get() {
        let parse = [];
        if (formData.otherCertFiles) {
            parse = JSON.parse(formData.otherCertFiles);
        }
        return parse;
    },
    set(newValue) {
        formData.otherCertFiles = JSON.stringify(newValue)
    }
})
const idCardFilesArr = computed({
    get() {
        let parse = [];
        if (formData.idCardFiles) {
            parse = JSON.parse(formData.idCardFiles);
        }
        return parse;
    },
    set(newValue) {
        formData.idCardFiles = JSON.stringify(newValue)
    }
})

const isDetail = computed(() => {
    if (mode.value == 'add') {
        return true
    } else if (mode.value == 'edit') {
        return true
    } else {
        return false
    }
})

const formData = reactive({
    id: '',
    realname: '',
    mobile: '',
    idNumber: '',
    lawOffice: '',
    createdAt: '',

    gender: '',
    aId: '',
    areaName: '',
    jobType: '',
    workBeginDate: '',
    workYears: '',

    skilledField: '',
    businessScope: '',

    lawyerCertFiles: '',
    otherCertFiles: '',
    idCardFiles: '',

    userId: '',
    avatar: '',
    lawOfficeAddress: '',
    cityId: '',
    areaId: '',
    status: '',
    refuseRemark: '',
    deletedAt: '',
    checkTime: '',
    checkUser: '',
    commissionRate: '',
    linkAddress: '',
    lawyerCertNumber: '',
    salesman: '',
})

const formRules = {
    id: [
        {
            required: true,
            message: '请输入',
            trigger: ['blur']
        }
    ],
    aId: [
        {
            required: true,
            message: '请输入地区ID',
            trigger: ['blur']
        }
    ],
    userId: [
        {
            required: true,
            message: '请输入用户ID',
            trigger: ['blur']
        }
    ],
    realname: [
        {
            required: true,
            message: '请输入真实姓名',
            trigger: ['blur']
        }
    ],
    avatar: [
        {
            required: true,
            message: '请输入形象照片（个人中心设置）',
            trigger: ['blur']
        }
    ],
    gender: [
        {
            required: true,
            message: '请输入性别 1男 2女',
            trigger: ['blur']
        }
    ],
    idNumber: [
        {
            required: true,
            message: '请输入身份证号',
            trigger: ['blur']
        }
    ],
    mobile: [
        {
            required: true,
            message: '请输入联系方式-手机号',
            trigger: ['blur']
        }
    ],
    lawOffice: [
        {
            required: true,
            message: '请输入所属律所',
            trigger: ['blur']
        }
    ],
    lawOfficeAddress: [
        {
            required: true,
            message: '请输入律所地址',
            trigger: ['blur']
        }
    ],
    cityId: [
        {
            required: true,
            message: '请输入所属城市id',
            trigger: ['blur']
        }
    ],
    areaId: [
        {
            required: true,
            message: '请输入所属地区id',
            trigger: ['blur']
        }
    ],
    workBeginDate: [
        {
            required: true,
            message: '请选择从业开始时间',
            trigger: ['blur']
        }
    ],
    workYears: [
        {
            required: true,
            message: '请输入工作年限',
            trigger: ['blur']
        }
    ],
    jobType: [
        {
            required: true,
            message: '请选择执业分类 1专职律师 2兼职律师',
            trigger: ['blur']
        }
    ],
    lawyerCertFiles: [
        {
            required: true,
            message: '请输入职业证书文件',
            trigger: ['blur']
        }
    ],
    otherCertFiles: [
        {
            required: true,
            message: '请输入其他辅助证书文件',
            trigger: ['blur']
        }
    ],
    idCardFiles: [
        {
            required: true,
            message: '请输入身份证照片',
            trigger: ['blur']
        }
    ],
    skilledField: [
        {
            required: true,
            message: '请输入擅长领域',
            trigger: ['blur']
        }
    ],
    businessScope: [
        {
            required: true,
            message: '请输入业务范围',
            trigger: ['blur']
        }
    ],
    status: [
        {
            required: true,
            message: '请选择0待审核 1审核通过 2被驳回',
            trigger: ['blur']
        }
    ],
    refuseRemark: [
        {
            required: true,
            message: '请输入驳回原因',
            trigger: ['blur']
        }
    ],
    deletedAt: [
        {
            required: true,
            message: '请选择删除时间',
            trigger: ['blur']
        }
    ],
    checkTime: [
        {
            required: true,
            message: '请选择审核时间',
            trigger: ['blur']
        }
    ],
    checkUser: [
        {
            required: true,
            message: '请输入审核人',
            trigger: ['blur']
        }
    ],
    commissionRate: [
        {
            required: true,
            message: '请输入佣金比例',
            trigger: ['blur']
        }
    ],
    createdAt: [
        {
            required: true,
            message: '请选择创建时间',
            trigger: ['blur']
        }
    ],
    linkAddress: [
        {
            required: true,
            message: '请输入联系地址（个人中心设置）',
            trigger: ['blur']
        }
    ],
    lawyerCertNumber: [
        {
            required: true,
            message: '请输入职业证书编号',
            trigger: ['blur']
        }
    ],
    salesman: [
        {
            required: true,
            message: '请输入所属销售',
            trigger: ['blur']
        }
    ],
}

const batchFileDelete = async (img?: string, imagArr?: string[], imageStr?: string) => {

    let imagArrNew = imagArr?.filter((item: string) => {
        return item !== img;
    })
    if (imageStr === formData.lawyerCertFiles) {
        formData.lawyerCertFiles = JSON.stringify(imagArrNew)
    } else if (imageStr === formData.otherCertFiles) {
        formData.otherCertFiles = JSON.stringify(imagArrNew)
    } else if (imageStr === formData.idCardFiles) {
        formData.idCardFiles = JSON.stringify(imagArrNew)
    }
}

const handlePreview = (url: string) => {
    previewUrl.value = url
    showPreview.value = true
}

const handleSubmit = async () => {
    await formRef.value?.validate()
    const data: any = { ...formData }
    mode.value == 'edit' ? await lawyerEdit(data) : await lawyerAdd(data)
    popupRef.value?.close()
    feedback.msgSuccess('操作成功')
    emit('success')
}

const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
}

const setFormData = async (data: Record<string, any>) => {
    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
}

const getDetail = async (row: Record<string, any>) => {
    const data = await lawyerDetail({
        id: row.id
    })
    setFormData(data)
}

const handleClose = () => {
    emit('close')
}

defineExpose({
    open,
    setFormData,
    getDetail
})
</script>
